package calculator;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.html.HtmlWriter;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.rtf.RtfWriter2;
import dataview.ACapo;
import dataview.Data;
import dataview.EasyFile;
import dataview.FormatoReport;
import dataview.NuovaPagina;
import dataview.Paragrafo;
import dataview.Parte;
import dataview.Report;

public class GeneraReport {
	public static String REPORT_DIR = System.getProperty("user.home") + "/easycooking/report/";
	
	public static EasyFile generaFile(Report contenuto, FormatoReport formato) throws DocumentException {
		return generaFile(contenuto, formato, REPORT_DIR + "reportCibi_" + Data.toReportFormat());
	}
	
	public static EasyFile generaFile(Report contenuto, FormatoReport formato, String path) throws DocumentException {
		EasyFile dir = new EasyFile(REPORT_DIR);
		dir.mkdir();
		switch (formato) {
			case txt:
				return generaFileTxt(contenuto, path);
			case pdf:
			case html:
			case rtf:
				return generaFilePdfHtmlRtf(contenuto, formato, path);
			default:
				throw new IllegalArgumentException();
		}
	}
	
	private static EasyFile generaFilePdfHtmlRtf(Report contenuto, FormatoReport formato, String path) throws DocumentException {
		String titolo = "EasyCooking Report";
		EasyFile file = new EasyFile(path);
//		EasyFile file = new EasyFile(path + "." + formato.toString());
		FileOutputStream fs = null;
		try {
			fs = new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		Document doc = new Document();
		doc.addAuthor("ATPC");
		doc.addCreationDate();
		if (formato == FormatoReport.html)
			HtmlWriter.getInstance(doc, fs);
		else if (formato == FormatoReport.pdf)
			PdfWriter.getInstance(doc, fs);
		else if (formato == FormatoReport.rtf) RtfWriter2.getInstance(doc, fs);
		doc.addTitle(titolo);
		doc.open();
		for (Parte parte : contenuto.getParti()) {
			if (parte instanceof Paragrafo)
				doc.add(((Paragrafo)parte).getReportElement());
			else if (parte instanceof ACapo)
				doc.add(((ACapo)parte).getReportElement());
			else if (parte instanceof NuovaPagina) doc.newPage();
		}
		doc.close();
		return file;
	}
	
	private static EasyFile generaFileTxt(Report contenuto, String path) {
		EasyFile file = new EasyFile(path/* + ".txt"*/);
		PrintStream ps = null;
		try {
			ps = new PrintStream(path/* + ".txt"*/);
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		for (Parte parte : contenuto.getParti()) {
			if (parte instanceof Paragrafo)
				ps.append(((Paragrafo)parte).getContenuto());
			else if (parte instanceof ACapo)
				ps.append("\n");
			else if (parte instanceof NuovaPagina) ps.append("\n\n\n");
		}
		return file;
	}
}
